﻿' oi bibliothikes pou xrisimopoiuntai stin Forma
Imports System.Diagnostics
Imports System.Drawing
Imports System.IO
Imports System.IO.File
Imports System.Windows.Forms
Imports Lucene.Net.Analysis.Standard
Imports Lucene.Net.Documents
Imports Lucene.Net.Documents.Field
Imports Lucene.Net.Index
Imports Lucene.Net.QueryParsers
Imports Lucene.Net.Search
Imports Lucene.Net.Analysis
Imports System.Configuration
Imports Lucene.Net.Store.FSDirectory
Imports System.Data.OleDb
Imports System.Data.DataSet

Public Class Form1

    Inherits System.Windows.Forms.Form

    'proto tab gia anazitisi me ti bibliothiki lucen.net se ena sigkekrimeno fakelo diladi monopati pou tou kathorizoume
#Region "first tab"
    'orismos atributes pou einai xrisima stin euritiarisi kai anazitisi
    Private searcher1 As IndexSearcher = Nothing 'to antikeimeno auto briskete sthn bibliothiki tis lucen
    Private pathIndex As String
    Private indexWriter1 As IndexWriter 'to antikeimeno auto briskete sthn bibliothiki tis lucen
    'Private searcher As IndexSearcher = Nothing
    Private bytesTotal As Long = 0
    Private countTotal As Integer = 0 ' sunolikos arithmos twn arxeiwn
    Private countSkipped As Integer = 0 ' arithos arxeiwn pou prospelastikan
    Private patterns As String() = {"*.doc", "*.xls", "*.ppt", "*.htm", "*.txt"} ' eidi arxeiwn sta opoia ginetai h anazhthsh
    Private imageListDocuments As SystemImageList ' antikeimeno tis class SystemImageList h opoia perexei tis eikones tvn arxeivn poy tha emfanizontai sta apotelesmata

    'dimiourgia tou index diladi euritiriou kai elegxos gia errors
    Private Sub checkIndex()
        Try
            searcher1 = New IndexSearcher(Me.pathIndex) 'dimiourgei ton idex basi toy path poy ebale sto antistoixo box o xristis
            searcher1.Close()
            'Minima sfalmatos tou index
        Catch generatedExceptionName As IOException
            status("Το Ευρετήριο δεν υπάρχει ή εχει καταστράφει. Παρακαλώ προχωρήστε σε ανακατασκευή του.", True)
            Return
        End Try

        Dim msg As String = [String].Format(" Το Ευρετήριο είναι έτοιμο. Περιέχει {0} αρχεία.", searcher1.MaxDoc())
        status(msg)
    End Sub

    'anadromiki methodo status 
    Private Sub status(ByVal msg As String)
        status(msg, False)
    End Sub

    'yperfortomeni status gia elegxo tou index kai xirismo error 
    Private Sub status(ByVal msg As String, ByVal [error] As Boolean)
        Me.labelStatus.Text = msg
        ' an sto index yparxei problima to minima emfanizetai me ble fonto
        If [error] Then
            Me.labelStatus.ForeColor = Color.Blue
        Else
            Me.labelStatus.ForeColor = DefaultForeColor
        End If

        Application.DoEvents()
    End Sub
    'methodos search pernei to index pou dimiourgithike kai ginetai anazitisi me to onoma arxeiou pou dothike
    Private Sub search()
        Dim start As DateTime = DateTime.Now

        Try
            searcher1 = New IndexSearcher(Me.pathIndex)
            'Minima lathous pou pianei to exception
        Catch ex As IOException
            MessageBox.Show("Το Ευρετήριο δεν υπάρχει ή εχει καταστράφει. Παρακαλώ ξανακάντε ανακατασκευή του index." & vbCr & vbLf & vbCr & vbLf & "Λεπτομέρειες:" & vbCr & vbLf + ex.Message)
            Return
        End Try

        'katharismos apotelesmatwn 
        Me.ViewResults.Items.Clear()

        'an to box tis anazitisis einai keno den bgazei kapoio apotelesma
        If Me.textBoxSearch.Text.Trim(New Char() {" "c}) = [String].Empty Then
            Return
        End If

        'orismos tou query gia anazitisi
        Dim query As Query = QueryParser.Parse(Me.textBoxSearch.Text, "text", New StandardAnalyzer())


        Dim hits As Hits = searcher1.Search(query) 'metritis 


        For i As Integer = 0 To hits.Length() - 1 ' gia oses fores brethei ayto poy anazhta o xristis

            Dim doc As Document = hits.Doc(i) ' edw mesa periexetai to euretirio mas

            ' dimiourgia seiras me ta apotelesmata twn dedomenwn
            Dim filename As String = doc.[Get]("title")
            Dim path__1 As String = doc.[Get]("path")
            Dim folder As String = Path.GetDirectoryName(path__1)
            Dim di As New DirectoryInfo(folder)

            'prosthiki anistoixou eikonidioy sthn seira toy apotelesmatos poy de;ixnei ton typo toy px an einai word klp..
            Dim item As New ListViewItem(New String() {Nothing, filename, di.Name, hits.Score(i).ToString()})
            item.Tag = path__1
            'item.ImageIndex = imageListDocuments.IconIndex(filename)

            'prosthiki ana seira stin lista apotelesmatwn
            Me.ViewResults.Items.Add(item)
            Application.DoEvents()
        Next
        searcher1.Close()

        Dim searchReport As String = [String].Format("Αναζήτηση {0}. Βρέθηκαν {1} αντικείμενα.", (DateTime.Now - start), hits.Length())
        status(searchReport)
    End Sub
    'Orismos twn methodwn sta click pou ginontai gia to kathe koumpi stin forma

    'epilogi path pros dimiourgia index
    Private Sub BrowseButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BrowseButton.Click
        Me.FolderBrowserDialog1.SelectedPath = Me.textBoxPath.Text 'anoigma enos dialog parathurou sto xristi gia thn epilogh toy path tou arxeiou poy tha xrisimopoieithei gia eurethrio 
        If Me.FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            Me.textBoxPath.Text = Me.FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    'katharismos tou index
    Private Sub CleanButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CleanButton.Click
        Directory.Delete(Me.pathIndex, True)
        checkIndex()
    End Sub

    'koumpi anazitis 
    Private Sub Search_Button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Search_Button.Click
        search()
        '			this.dataGridResults.DataSource = this.results;
    End Sub
   
    'me diplo klik anoigei to arxeio se neo parathuro
    Private Sub ViewResults_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ViewResults.DoubleClick
        If Me.ViewResults.SelectedItems.Count <> 1 Then
            Return
        End If
        Dim path As String = DirectCast(Me.ViewResults.SelectedItems(0).Tag, String)
        Process.Start(path)
    End Sub

    'koumpi anakataskeueis euretiriou
    Private Sub IndexButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IndexButton.Click
        indexWriter1 = New IndexWriter(Me.pathIndex, New StandardAnalyzer(), True)
        'metrites ksana arxikopoihsh toys
        bytesTotal = 0
        countTotal = 0
        countSkipped = 0

        enableControls(False)

        Dim di As New DirectoryInfo(Me.textBoxPath.Text)
        'pernume to kainoyrgio path gia na kanoyme ksana to eyretirio mas 
        Dim start As DateTime = DateTime.Now

        addFolder(di) ' prosthetei ta arxeia toy kainoyrgiou path sta palia an uparxoun dhladh an den exoun sbhstei me to buttonclean

        Dim summary As String = [String].Format("ΟΚ. Indexed {0} αρχεία ({1} bytes). Παραλείφθηκαν {2} αρχεία.", countTotal, bytesTotal, countSkipped)
        summary += [String].Format(" Πάρθηκαν {0}", (DateTime.Now - start))
        status(summary)
        enableControls(True)

        indexWriter1.Optimize()
        indexWriter1.Close()
    End Sub

    'prosthiki fakelou
    Private Sub addFolder(ByVal directory As DirectoryInfo)
        'briskei ola ta arxeia 
        For Each pattern As String In patterns
            For Each fi As FileInfo In directory.GetFiles(pattern)
                ' kanei skip arxeia tou office
                If fi.Name.StartsWith("~") Then
                    Continue For
                End If

                Try
                    addOfficeDocument(fi.FullName)

                    ' enimerosi twn metritwn
                    Me.countTotal += 1
                    Me.bytesTotal += fi.Length

                    ' deixnei ta arxeia pou prosthetikan
                    status(fi.FullName)
                Catch generatedExceptionName As Exception
                    ' i analisi kai i eyretiriasi den itan epitixis to arxeio egine skip
                    Me.countSkipped += 1
                    status(" Εγίνε Skip: " + fi.FullName)
                End Try
            Next
        Next

        ' prosthiki ypofakelon
        For Each di As DirectoryInfo In directory.GetDirectories()
            addFolder(di)
        Next
    End Sub
    ' methodos prosthikis ypofakelon 
    Private Sub addOfficeDocument(ByVal path__1 As String)
        Dim doc As New Document()
        Dim filename As String = Path.GetFileName(path__1)

        doc.Add(Field.UnStored("text", Parser.Parse(path__1)))
        doc.Add(Field.Keyword("path", path__1))
        doc.Add(Field.Text("title", filename))
        indexWriter1.AddDocument(doc)
    End Sub


#End Region



    'sti fortosi tis arxikis formas to textBox pou brisketai to path bazei os arxiko path tin topothesia "My documents" tou xristi
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.textBoxPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        Me.pathIndex = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ADOPSE")
        checkIndex()
    End Sub
    'Energopoisi to controls pou dimiourgithikan
    Private Sub enableControls(ByVal enable As Boolean)
        Me.textBoxPath.Enabled = enable
        Me.IndexButton.Enabled = enable
        Me.BrowseButton.Enabled = enable
        Me.CleanButton.Enabled = enable
    End Sub

   
End Class